/* 
 * File:   resource.cpp
 * Author: Faraj
 * 
 * Created on May 5, 2013, 6:38 PM
 */
#include "resource.h"

vector<lib::application> lib::resource::_applications;

void lib::resource::conf_apps(config *conf, string root_key){
    common::log::trace("resource.set_applications");
    vector<string> keys = conf->keys(root_key);
    for(vector<string>::iterator ikey = keys.begin(); ikey != keys.end(); ++ikey){        
        lib::application *app = new application(*ikey);
        root_key = root_key + "." + *ikey;
        vector<string> param_keys = conf->keys(root_key + ".param");
        for(vector<string>::iterator iparamkey = param_keys.begin(); iparamkey != param_keys.end(); ++iparamkey){
            app->add_param(*iparamkey, conf->lookup(root_key + ".param." + *iparamkey));
        }
        app->set_ext(conf->lookup(root_key + ".ext"));
        lib::resource::_applications.push_back(*app);
    }
}

lib::resource::resource(string path) {
    common::log::trace("resource.resource");
    _path = path;
}

lib::resource::~resource() {
    common::log::trace("resource.~resource");
    close();
}

bool lib::resource::is_data_file(){
    common::log::trace("resource.is_data_file");
    //check the filter
    return false;
}

bool lib::resource::open() {
    common::log::trace("resource.open path " + _path);
    _file.open(_path.c_str(), ios::in | ios::binary | ios::ate);
    _valid = _file && _file.is_open();
    if (_valid) {
        _size = _file.tellg();
    }else{
        common::log::warn("resource.load invalid resource " + _path);
    }
    return _valid;
}

FILE* lib::resource::get_fd(){
    common::log::trace("resource.get_fd");
    FILE *fd;
    fd = fopen(_path.c_str(), "rb");
    return fd;
}

bool lib::resource::close() {
    common::log::trace("resource.close");
    if (_file && _file.is_open()) {
        _file.close();
    }
    return !_file.is_open();
}

bool lib::resource::read() {
    common::log::trace("resource.read");
    _content = new char [_size];
    _file.seekg(0, ios::beg);
    _file.read(_content, _size);
}

void lib::resource::execute(){
    common::log::trace("resource.execute");
    if(!is_valid()){
        open();
    }
    if(is_valid()){
        read();
    }
    close();
}

char* lib::resource::get_content() {
    return _content;
}

int lib::resource::get_size() {
    return _size;
}

string lib::resource::get_path() {
    return _path;
}

bool lib::resource::is_valid() {
    return _valid;
}

bool lib::resource::is_valid_folder() {
    //@todo check valid folder
    return false;
}